package cn.tedu.egweibo6.controller;

import cn.tedu.egweibo6.base.response.JsonResult;
import cn.tedu.egweibo6.mapper.WeiboMapper;
import cn.tedu.egweibo6.pojo.bto.WeiboDTO;
import cn.tedu.egweibo6.pojo.entity.Weibo;
import cn.tedu.egweibo6.pojo.vo.UserVO;
import cn.tedu.egweibo6.pojo.vo.WeiboDetailVO;
import cn.tedu.egweibo6.pojo.vo.WeiboListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Slf4j
@Validated
@RestController
@Api(tags = "02.微博模块")
@RequestMapping("/v1/weibo/")
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    @ApiOperation(value = "发布微博")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody @Validated WeiboDTO weiboDTO,
                             @ApiIgnore HttpSession httpSession){
        log.debug("weiboDTO={}",weiboDTO);
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO,weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insert(weibo);

        return JsonResult.ok();
    }

    @ApiOperation(value = "微博首页列表")
    @GetMapping("selectIndex")
    public JsonResult selectIndex(){
        List<WeiboListVO> weiboListVOS = weiboMapper.selectIndex();
        return JsonResult.ok(weiboListVOS);

    }

    @ApiOperation(value = "微博详情页")
    @GetMapping("selectById")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "微博编号",required = true,dataType = "long"),
            @ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "string")
    })
    public JsonResult selectById(@Range(min = 200,max = 300,message = "微博编号必须在200~300之间")
                                    @RequestParam Long id, String username){
        log.debug("id={}",id);
        WeiboDetailVO weiboDetailVO =  weiboMapper.selectById(id);

        return JsonResult.ok(weiboDetailVO);
    }

}
